//------------------------------------------------------------------------------
//
// ...
// class: ClientReception 
// author: 喵大斯( as3er.net )
// created: 2015/8/27
// copyright (c) 2015 喵大斯( aosnow@yeah.net )
//
//------------------------------------------------------------------------------
/// <reference path='../core/jquery.d.ts'/>
/// <reference path='../core/jquery.extend.d.ts'/>
/// <reference path='../core/page_core.d.ts'/>
/// <reference path='../core/utils.ts'/>
/// <reference path='../core/submitter.d.ts'/>
/// <reference path='../core/pageset.d.ts'/>
/// <reference path='../core/datepicker.d.ts'/>
var ClientReception = (function () {
    //--------------------------------------------------------------------------
    //
    //  Class constructor
    //
    //--------------------------------------------------------------------------
    /**
     * 客户预约数据显示控制器
     * @param table 用于显示预约数据的表格 JQuery 对象
     * @param type 接待的类型（是否绑定预约记录）
     */
    function ClientReception(table, type) {
        if (type === void 0) { type = "with_reserve"; }
        //----------------------------------------
        // receptionKey
        //----------------------------------------
        /** 接待记录 key（当添加新记录时，此值始终为空） */
        this.receptionKey = "";
        this._table = table;
        this._type = type;
        //this.initTable();
    }
    //--------------------------------------------------------------------------
    //
    //	Class methods
    //
    //--------------------------------------------------------------------------
    ClientReception.prototype.initTable = function () {
        var _this = this;
        // 显示/隐藏客户预约数据资料
        var title = this._table.find("tr[rel='title']");
        title.css("cursor", "pointer");
        title.click(function () {
            _this.showOrHideDetailed();
        });
        // 初始阶段将HTML的行节点对象 缓存到变量中
        this._tableHtml = this._table.find("tr[rel='title'] ~ tr");
        this._tableHtml.find("tr[rel='title'] ~ tr").remove(); // 初始从表格中移除
        // 学员测评情况表单模板
        $("#tbl_student_temp").show();
        $("#student_test_recycle").show();
        // 初始化请求列表内容（只请求数据）
        this.update_student(true);
    };
    /**
     * 重置表单内容
     */
    ClientReception.prototype.resetHtmlContent = function () {
        var _this = this;
        this._table.find("tr:not(:first)").remove();
        this._table.append(this._tableHtml.clone(false));
        // 接待表单添加客户跟踪事件绑定
        this._table.find("#btnAddTracking").click(function () { _this.execTrackingHandler(); });
        update_row_bg(this._table);
        // 日期控件初始化
        var dp = this._table.find("#rep_date");
        ipt_dater_init(dp);
        dp.val(today());
        // 填充动态列表（读取数据库）
        this.update_student(false, true);
    };
    // 设置填充或清空接待数据
    ClientReception.prototype.setReception = function (d) {
        var _this = this;
        if (!empty(d)) {
            this.receptionKey = d.key;
            this.resetHtmlContent();
            $("#rep_worth").val(d.worth);
            $("#rep_feature").val(d.feature);
            $("#rep_date").html("<span class=\"stress unit hand\" id=\"rdate\">" + d.date + "</span>");
            $("#rep_user_box").html("<span class=\"stress unit hand\" id=\"ruser\">" + d.reception_ns + "</span>");
            $("#rep_region_box").html("<span class=\"stress unit hand\" id=\"region\">" + d.region_ns + "</span>");
            // 学员名单
            if (empty(this._student_html)) {
                if (!empty(this._student_jqXHR)) {
                    // 正在请求，尚未完成
                    this._student_jqXHR.then(function () {
                        _this.setStudentTestData(d,f);
                    });
                }
                else {
                    // 没有请求，立即发送请求学员列表
                    this.update_student(false, true, function () { _this.setStudentTestData(d); });
                }
            }
            else {
                // 直接设置学员测评数据
                this.setStudentTestData(d);
            }
        }
        else {
            this.receptionKey = null;
            this._table.find("tr:not(:first)").remove();
        }
    };

    // 设置更新学员测评数据
    ClientReception.prototype.setStudentTestData = function (d,f) {
    	 var data = d;
         var box = $("#rep_student_box");
             // 勾选学员名单
             var li = box.find("ul > li[rel='" +data+ "']");
             li.find(":checkbox").prop("checked", true);
             // 创建测评表单
             this.setNewStudent(data,f);
             this.requestStudentSingleInfo(data,f);
    };
    
    //--------------------------------------------------------------------------
    //
    // 学员测评数据维护
    //
    //--------------------------------------------------------------------------
    ClientReception.prototype.setNewStudent = function (key, i) {
        // 克隆表单
        this.copyStudentTemp(key, i);
        // 设置学员基本数据
        var tbl = $("#" + key);
        // 学员情况包含学员资料和接待情况（来源于tg_student及tg_reception）
        tbl.attr("rel", key);
    };
    ClientReception.prototype.requestStudentSingleInfo = function (key) {
        var _this = this;
        $.post(contextPath+"/index/consultant_student_search.json", { key: key }, function (d) {
            _this.setStudentInfo(d);
        }, "json");
    };
        
    ClientReception.prototype.setStudentInfo = function (d) {
    	var stu = d.stuList;
    	var stulist = stu[0];
        var tbl = $("#student_test_list").find("#" + stulist.keyname);
        if (!tbl.exist())
            tbl = $("#student_test_recycle").find("#" + stulist.keyname);
        if (tbl.exist()){
            var name = defaultVal(d.nickname);
            var sex = defaultVal(d.sex);
            var age = defaultVal(d.age);
            tbl.find("[rel='btnStudent']").attr("rev", stulist.pkey);
            tbl.find("tr:first th").html("学员 [ " + name + " ] 的测评情况");
            tbl.find("[rel='student_info']").html(name + "，" + sex + "，" + age + " 岁");
        }
    };
    ClientReception.prototype.requestStudentInfo = function (key) {
        var _this = this;
        submitter.post("student_search.php", { key: key }, function (d) {
            if (d.err == 0) {
                var size = parseInt(d['size']);
                for (var i = 0; i < size; i++) {
                    var v = d[i];
                    // 更新表单中的学员基本资料（姓名，性别，年龄）
                    _this.setStudentInfo(v);
                    // 更新接待表单中学员列表的基本资料（复选框）
                    _this.updateStudentListInfo(v);
                }
            }
            else {
                infopad.err(d.msg);
            }
        }, "json");
    };
    // 设置指定表单的学员接待数据
    ClientReception.prototype.setStudentData = function (tbl, d) {
        tbl.find("[rel='testuser'] select").val(d.testuser);
        tbl.find("#price").val(d.price);
        tbl.find("#moneylog").val(d.moneylog);
        tbl.find("#reason").val(d.reason);
        tbl.find("#remark").val(d.remark);
        // 设置当前选择的测评完成情况选择
        var selects = (!empty(d.result) ? d.result : "").split(",");
        var ps = tbl.find("[rel='result'] > div").find("p[rel^='TR_']");
        // 过滤兼容没有选择的旧记录
        if (selects.length == ps.length) {
            ps.each(function (id) {
                var val = selects[id];
                if (val) {
                    var txt = "";
                    if (val.indexOf(":") != -1) {
                        var tmp = val.split(":");
                        val = tmp[0];
                        txt = tmp[1];
                    }
                    $(this).find(":radio[value=" + val + "]").prop("checked", true);
                    if ($(this).find("input[name^='TXT_']").length > 0)
                        $(this).find("input[name^='TXT_']").val(txt);
                }
            });
        }
    };
    ClientReception.prototype.copyStudentTemp = function (id, i) {
        var _this = this;
        var temp = $("#tbl_student_temp");
        var container = $("#student_test_list");
        container.append(temp.clone(true));
        var tbl = container.find("table:last");
        tbl.show();
        tbl.attr("id", id);
        // 学员表单头部点击事件
        tbl.find("tr:first > th").click(this.nameRowClick);
        tbl.find("tr:first > th").css("cursor", "pointer");
        tbl.find("tr:first > th").trigger("click");
        // 弹出学员资料编辑窗口
        tbl.find("[rel='btnStudent']").click(function (e) { _this.editStudentHandler(e); });
        // 测评项目调查表隐藏、显示
        tbl.find("[rel='btnShowVote']").show();
        tbl.find("tr:not(:first)").show();
        tbl.find("[rel='btnArrow']").add(tbl.find("[rel='btnShowVote']")).click(function () {
        tbl.find("[rel='result'] > div").find("p[rel^='TR_']").find(":radio").attr('id');
       
        tbl.find( "[rel='result'] > div" ).find( "p[rel^='TR_']" ).children(".rect").each( function( id ){
        	var ind = $(this).find(":radio").attr('name');
        	var im = ind+'_'+i
        	var ids = $(this).find(":radio").attr('id');
        	var fo = $(this).find(".hand").attr('for');
        	$(this).find(":radio").attr('name',im);
        	$(this).find(":radio").attr('id',ids+"_"+i);
        	$(this).find(".hand").attr('for',fo+"_"+i);
        });
        	var vote = tbl.find("[rel='result'] > div");
            if (vote.visible()) {
                vote.hide();
                tbl.find("[rel='btnShowVote']").show();
            }
            else {
                vote.show();
                tbl.find("[rel='btnShowVote']").hide();
            }
        });
        tbl.find("[rel='btnArrow']").trigger("click");
        
        
    };
    // 点击表头时，隐藏表体
    ClientReception.prototype.nameRowClick = function () {
        var tbl = $(this).parent().parent();
        var show = tbl.find("tr:not(:first)").visible();
        var trs = tbl.find("tr:not(:first)");
        show ? trs.hide() : trs.show();
    };
    // 分析返回接待表单数据
    ClientReception.prototype.getFormData = function () {
        var _this = this;
        var data = {};
        data.client = this.clientKey;
        data.key = this.receptionKey;
        data.rdate = this._table.find("#rep_date").val();
        data.ruser = this._table.find("#rep_user").val();
        data.region = this._table.find("#rep_region").val();
        data.worth = this._table.find("#rep_worth").val();
        data.feature = this._table.find("#rep_feature").val();
        var student = {};
        $("#student_test_list").find(" > table").each(function (index, el) {
            var key = $(el).attr("id");
            var data = _this.getStudentData($(el));
            // 若返回数据为空，则跳过这个表单
            if (data == false)
                return true;
            student[key] = data;
        });
        data.student = JSON.stringify(student);
        return data;
    };
    /**
     * 收集格式化指定表单的学员接待数据
     */
    ClientReception.prototype.getStudentData = function (tbl) {
        var data = {};
        data.key = tbl.attr("id");
        data.testuser = tbl.find("[rel='testuser'] select").val();
        data.price = tbl.find("#price").val();
        data.moneylog = tbl.find("#moneylog").val();
        data.reason = tbl.find("#reason").val();
        data.remark = tbl.find("#remark").val();
        // 若测评老师未选择则视为无效记录
        if (empty(data.testuser)
            && empty(data.price)
            && empty(data.moneylog)
            && empty(data.reason)
            && empty(data.remark))
            return false;
        // 测评完成情况选择列表
        var selects = [];
        tbl.find("[rel='result'] > div").find("p[rel^='TR_']").each(function () {
            var name = $(this).attr("rel");
            var ns = name.split("_");
            var id = ns[1];
            var val = $(this).find(":radio:checked").val();
            var remark = $(this).find("input[name='TXT_" + id + "']").val();
            if (typeof (val) == 'undefined') {
                //infopad.err( "测评完成情况第 " + name.replace( "TR_", "" ) + " 条未选择。" );
                val = 0;
            }
            if (!empty(remark)) {
                remark = remark.replace(/,/ig, "，"); // 英文逗号换成中文的，以免打乱数据分隔符
                val = val + ":" + remark;
            }
            // 选择值：1-是，2-否，0-未选择
            selects.push(val);
        });
        data.result = selects.join(",");
        return data;
    };
    // 刷新当前表单的学员列表
    ClientReception.prototype.update_student = function (onlyRequest, onlySet, callback) {
        var _this = this;
        if (onlyRequest === void 0) { onlyRequest = false; }
        if (onlySet === void 0) { onlySet = false; }
        var box = this._table.find("#rep_student_box");
        if (onlySet && !empty(this._student_html)) {
            box.html(this._student_html);
        }
        else {
            var back = function (d) {
                // 返回结果，重置 XHR，不论是否正确结果
                _this._student_jqXHR = null;
                if (d.err == 0) {
                    var size = parseInt(d['size']);
                    var html = "";
                    for (var i = 0; i < size; i++) {
                        var v = d[i];
                        var info = v.nickname + '， ' + v.sex + '， ' + v.age + ' 岁';
                        html += "<li rel='" + v.key + "' class='stress rect' style='list-style:none;float:left;width:200px;margin:2px;'>\n\t\t\t\t\t\t\t\t<label><input type='checkbox' rel='" + v.key + "'><span>" + info + "</span></label>\n\t\t\t\t\t\t\t</li>";
                    }
                    var isDataEmpty = empty(html);
                    if (isDataEmpty) {
                        html = "<em class=\"caption\" style=\"color:#ff3300;\">\uFF08\u5BA2\u6237\u540D\u4E0B\u65E0\u767B\u8BB0\u5B66\u5458\uFF09</em>";
                    }
                    else {
                        html = "<ul id='rep_student'>" + html + "</ul>";
                    }
                    if (!onlyRequest) {
                        box.html(html);
                    }
                    if (!isDataEmpty)
                        _this._student_html = html;
                    if ($.isFunction(callback) && !isDataEmpty)
                        callback(html);
                    // 弹出学员资料编辑窗口
                    box.find(":checkbox").change({ cls: _this }, _this.studentSelectHandler);
                }
                else {
                    infopad.err(d.msg);
                }
            };
            // 若当前已经存在未结束的请求，则中断请求
            if (!empty(this._student_jqXHR))
                this._student_jqXHR.abort();
            // 发送新的请求
            //this._student_jqXHR = submitter.post("student_search.php", { key: this.clientKey }, back, "json");
        }
    };
    // 刷新当前表单的单个学员资料
    ClientReception.prototype.updateStudentListInfo = function (d) {
        var box = $("#rep_student_box");
        var li = box.find("ul > li[rel='" + d.key + "']");
        var name = defaultVal(d.nickname);
        var sex = defaultVal(d.sex);
        var age = defaultVal(d.age);
        var info = name + "，" + sex + "，" + age + " 岁";
        if (!li.exist()) {
            var html = "<li rel='" + d.key + "' class='stress rect' style='list-style:none;float:left;width:200px;margin:2px;'>\n\t\t\t\t\t\t\t<label><input type='checkbox' rel='" + d.key + "'><span>" + info + "</span></label>\n\t\t\t\t\t\t</li>";
            box.find("ul").append(html);
        }
        else {
            li.find("label span").html(info);
        }
    };
    //--------------------------------------------------------------------------
    //
    //  Event handlers
    //
    //--------------------------------------------------------------------------
    ClientReception.prototype.showOrHideDetailed = function () {
        var trs = this._table.find("tr[rel='title'] ~ tr");
        var show = trs.eq(0).visible();
        show ? trs.hide() : trs.show();
    };
    // 当学员目标被选择或取消时
    ClientReception.prototype.studentSelectHandler = function (e) {
        var checked = $(this).prop("checked");
        var key = $(this).attr("rel");
        var tbl = $("#student_test_list");
        var tmpTbl = $("#student_test_recycle");
        if (checked) {
            // 显示到测评学员列表
            var temp = tmpTbl.find("#" + key);
            if (temp.exist()) {
                tbl.append(temp);
                // 从回收站拿回来的表单，默认隐藏内容
                tbl.find("#" + key).find("tr:not(:first)").hide();
            }
            else {
                e.data.cls.setNewStudent(key);
                e.data.cls.requestStudentSingleInfo(key);
            }
        }
        else {
            // 从列表移除到回收站容器，便于在恢复时能保留之前填写的数据
            var table = tbl.find("#" + key);
            if (table.exist()) {
                tmpTbl.append(table);
            }
        }
    };
    ClientReception.prototype.editStudentHandler = function (e) {
        var _this = this;
        if (empty(this.clientKey)) {
            infopad.err("请先指定目标客户，再编辑学员资料。");
            return;
        }
        var studentKey = $.trim($(e.currentTarget).attr("rev"));
        var url = "consultant_student.php?pkey=" + this.clientKey + "&student=" + studentKey + "&close=true";
        var title = "编辑学员资料";
        var id = "consultant_student_" + this.clientKey + "_" + studentKey;
        create_model(url, title, id, null, function () { _this.editStudentCloseHandler(); });
        open_model(id, true);
    };
    ClientReception.prototype.execTrackingHandler = function () {
        if (empty(this.clientKey)) {
            infopad.err("请先指定目标客户，再添加跟踪情况。");
            return;
        }
        var url = "consultant_client_tracking.php?key=" + this.clientKey;
        var title = "追加跟踪记录";
        var id = "consultant_client_tracking";
        create_model(url, title, id, 8999);
        open_model(id, true);
    };
    ClientReception.prototype.editStudentCloseHandler = function () {
        // 刷新学员资料
        if (this.clientKey != null) {
            this.requestStudentInfo(this.clientKey);
        }
    };
    /**
     * 需要绑定预约的接待类型
     * @type {string}
     */
    ClientReception.TYPE_WITH_RESERVE = "with_reserve";
    /**
     * 非预约接待类型
     * @type {string}
     */
    ClientReception.TYPE_WITHOUT_RESERVE = "without_reserve";
    return ClientReception;
})();
function defaultVal(val) {
    if (empty(val))
        return "-";
    return val;
}
